/**
 * Global Variables can be used in every
 *
 * --logger                an global object used for logging
 * --mongoose            an global connection object used for accessing mongodb
 * --mysqlClient        an global connection object used for accessing mysql
 * --cacheClient            an global connection object used for accessing memCache or Redis depending the globalParameters pre-defined
 */


/**
 * Module dependencies.
 */
var express = require('express')
    , http = require('http')
    , path = require('path')
    , expressValidator = require('express-validator');

var session = require('express-session');

var app = express();

app.use(session({
    secret: '66xiaoqu',
    name: '66xiaoqu',   //这里的name值得是cookie的name，默认cookie的name是：connect.sid
    cookie: {maxAge: 18000000},  //设置maxAge是80000ms，即80s后session和相应的cookie失效过期
    resave: false,
    saveUninitialized: true
}));


var bodyParser = require('body-parser');

if (!String.prototype.format) {
    String.prototype.format = function () {
        var args = arguments;
        return this.replace(/{(\d+)}/g, function (match, number) {
            return typeof args[number] != 'undefined'
                ? args[number]
                : match
                ;
        });
    };
}

//Set the environments for the application
app.set('port',3008);
app.set('views', __dirname + '/server/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(bodyParser.json());
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({secret: 'some secret key'}));

app.use(express.methodOverride());
app.use(express.multipart());

app.use(app.router);

//Specify the html folder used for client - browser
app.use(express.static(path.join(__dirname, 'public')));


//load the log4js configuration
require('./server/config/logging');

//Development only
console.log('env===' + process.env.NODE_ENV);
console.log('nodejs version' + process.version);
if ('DEV' == process.env.NODE_ENV) {
    require('./conf/globalParameters-DEV.js');
} else if ('TEST' == process.env.NODE_ENV) {
    require('./conf/globalParameters-TEST.js');
    console.log(backOfficeHost)
} else if ('PROD' == process.env.NODE_ENV) {
    require('./conf/globalParameters-PROD.js');
} else {
    logger.error('Please configure the environment Variable "NODE_ENV" in the OS system!');
    process.exit();
}

//node访问topic设置
//app.use("/topic", express.static(path.join(__dirname, resTopicPath())));

//Load the global parameters
require('./server/config/errorMessage');

//Load the database configuration
require('./server/config/database');

//Load the redis
require('./server/config/redis');

//Load the cache configuration;
require('./server/config/cache');


//load the log4js configuration
require('./server/config/messageQueue');

//load the log4js configuration
require('./server/config/passport');

//load the restClient
require('./server/config/restClient');

//load the fastDfsClient
require('./server/config/fdfsClient');

require('./server/config/hessian');
//load the baidu PushClient
require('./server/config/baiduPushClient');

//初始化权限列表
//require('./server/common/initialization/dataInit-step1');

/**
 * load all of the routes;
 */
//================================================
require('./server/routes/index')(app);
require('./server/routes/filter-route')(app);
//require('./server/routes/user-route')(app);
//require('./server/routes/masterData-route')(app);
require('./server/routes/question-route')(app);
//require('./server/routes/community-route')(app);
require('./server/routes/system-route')(app);
//require('./server/routes/activity-route')(app);
//require('./server/routes/score-route')(app);
//require('./server/routes/lottery-route')(app);
//require('./server/routes/backoffice/backOffice-rest-route')(app);
//require('./server/routes/backoffice/backOffice-adminUser-route')(app);
//require('./server/routes/backoffice/backOffice-marketing-route')(app);
//require('./server/routes/backoffice/backOffice-lottery-route')(app);
//require('./server/routes/backoffice/backOffice-user-route')(app);
//require('./server/routes/backoffice/backOffice-activity-route')(app);
//require('./server/routes/backoffice/backOffice-question-route')(app);
//require('./server/routes/backoffice/backOffice-serviceAsUser-route')(app);
//require('./server/routes/backoffice/backOffice-voucher-route')(app);
//require('./server/routes/backoffice/backOffice-lotteryActivity-route')(app);
//require('./server/routes/backoffice/backOffice-report-route')(app);
//require('./server/routes/backoffice/backOffice-banner-route')(app);
//require('./server/routes/backoffice/backoffice-scoreShop-route')(app);
//require('./server/routes/backoffice/backOffice-clientService-route')(app);
//require('./server/routes/mobile/shares-route')(app);
//require('./server/routes/mobile/downloadApp')(app);
//require('./server/routes/dosth-route')(app);
//require('./server/routes/backoffice/backOffice-geek-route')(app);
require('./server/routes/community-route')(app);
/*  宝宝树66小区sprint4    add   66后台结算佣金管理.导出订单 luolh  20171027  start   */
require('./server/routes/commission-route')(app);
/*  宝宝树66小区sprint4    add   66后台结算佣金管理.导出订单 luolh  20171027  end   */
//BI
require('./server/routes/BI/BI-dailyReporting-route')(app);
require('./server/routes/BI/BI-BDMarketing-route')(app);
require('./server/routes/BI/BI-Product-route')(app);
require('./server/routes/BI/BI-CSOps-route')(app);
//================================================

// opm2.0
require('./server/routes/mis/system-route')(app);
require('./server/routes/mis/community-route')(app);
require('./server/routes/mis/master-route')(app);
require('./server/routes/mis/region-route')(app);
require('./server/routes/mis/appuser-route')(app);
require('./server/routes/mis/operate-route')(app);
require('./server/routes/mis/common-route')(app);
require('./server/routes/mis/question-route')(app);
require('./server/routes/mis/market-route')(app);
require('./server/routes/mis/score-route')(app);

//心愿
//require('./server/routes/weixin/wish-route')(app);
//心愿 Backoffice
require('./server/routes/mis/weixin/wish-route')(app);
/*  宝宝树66小区二次改造-定时任务    mod   guo.xiaomin  20170906   start   */
require('./server/routes/mtOrder-route')(app);
/*  宝宝树66小区二次改造-定时任务    mod   guo.xiaomin  20170906   start   */

// commission
/*  宝宝树66小区sprint4    add   66后台-订单总佣金 wangcan  20171026  start */
require('./server/routes/commission/orderCommision-route')(app);
/*  宝宝树66小区sprint4    add   66后台-订单总佣金 wangcan  20171026  end */

/*  宝宝树66小区sprint4    add   66后台-某天大使佣金 wangcan  20171031  start */
require('./server/routes/commission/ambCommision-route')(app);
/*  宝宝树66小区sprint4    add   66后台-某天大使佣金 wangcan  20171031  end */

/*  宝宝树66小区四次改造-佣金    mod   guo.xiaomin  20171022   start   */
require('./server/routes/commission-route')(app);
/*  宝宝树66小区四次改造-佣金    mod   guo.xiaomin  20171022   start   */


/*  宝宝树66小区五次改造-运维模块    mod   guo.xiaomin  20171203   start   */
require('./server/routes/operation-route')(app);
/*  宝宝树66小区五次改造-运维模块    mod   guo.xiaomin  20171203   start   */
/*  宝宝树66小区五次改造-运维模块    mod   guo.xiaomin  20171203   start   */
require('./server/routes/userInvitation-route')(app);
/*  宝宝树66小区五次改造-运维模块    mod   guo.xiaomin  20171203   start   */

//================================================

if (BasicAuthen == 'Yes') {
    //Authenticate the request session;
    app.use(express.basicAuth(function (user, pass) {
        return user === '66xiaoqu' && pass === '66xiaoqu';
    }));
}

if (enableMultiProcessor == 'Yes') {
    //多进程模式
    /**
     * 先判断当前进程是否为主进程（cluster.isMaster），如果是的，就按照CPU的核数，新建若干个worker进程；
     * 如果不是，说明当前进程是worker进程，则在该进程启动一个服务器程序。
     */
    var cluster = require('cluster');
    var os = require('os');

    if (cluster.isMaster) {
        for (var i = 0, n = os.cpus().length; i < n; i += 1) {
            cluster.fork();
        }
    }
    else {
        httpServer = http.createServer(app);
        logger.info('Starting the back-end server....');
        //================================================
        httpServer.listen(app.get('port'), function () {
            logger.info('Back-end server listening on port for Http Request: ' + app.get('port') + '...');
        });
    }

} else {

    //单进程模式
    httpServer = http.createServer(app);
    httpServer.setMaxListeners(0);
    logger.info('Starting the back-end server....');
    //================================================
    httpServer.listen(app.get('port'), function () {
        logger.info('Back-end server listening on port for Http Request: ' + app.get('port') + '...');
    });

}
process.on('uncaughtException', function (err) {
    logger.error('Caught exception: ' + err);
});

/*  宝宝树66小区二次改造-定时任务    mod   guo.xiaomin  20170921   start   */
// 服务器启动/重启的时候执行一次
function scheduleFun(){
    var uri ='http://' + 'localhost:' + app.get('port') + '/rest/v1.0/mtOrder/mtOrderSchedule';
    logger.info(uri);
    http.get(uri, function(res) {
        logger.info("定时任务启动成功,状态: " + res.statusCode);
    }).on('error', function(e) {
        logger.info("定时任务启动失败: " + e.message);
    });
}
scheduleFun();
/*  宝宝树66小区二次改造-定时任务    mod   guo.xiaomin  20170921   end   */
